package cate.game.db.facade;

import cate.game.db.mongo.kv.KvDao;
import cate.game.db.mongo.kv.KvMongo;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Optional;

@Slf4j
public class KvDaoFacade {
    private final KvDao dao;

    public KvDaoFacade(KvDao dao) {
        this.dao = dao;
    }

    public void save(KvMongo kv) {
        try {
            dao.save(kv);
        } catch (Exception e) {
            log.error("保存KV到MongoDB的时候发生问题, 当前 key: {}", kv.key, e);
        }
    }

    @SuppressWarnings("unchecked")
    public <T extends KvMongo> T get(String key) {
        try {
            Optional<KvMongo> optional = dao.findById(key);
            T value = (T) optional.orElse(null);
            log.debug("[KV读取观察] key={}, value={}", key, value);
            return value;
        } catch (Exception e) {
            log.error("读取key="+key+"的KV时出错", e);
            return null;
        }
    }

    public <T extends KvMongo> List<T> findByKeyPrefix(String keyPrefix, Class<T> eleClz) {
        return dao.findByKeyPrefix(keyPrefix, eleClz);
    }

    public void delete(String key) {
        dao.deleteById(key);
    }
}
